// $URL: http://mingw-lib.googlecode.com/svn/trunk/working/avcodec_to_widget_7/nbr.h $
// $Rev: 250 $
// $Author: akio.miyoshi $
// $Date:: 2010-07-20 23:06:06 +0000#$

#ifndef NETWORKBATCHREQUEST_H
#define NETWORKBATCHREQUEST_H

#include <QtCore>
#include <QtNetwork>

class NetworkWaiter : public QThread
{
    Q_OBJECT
public:
    NetworkWaiter(QNetworkReply *a_reply, bool a_buffer_mode = false);
    ~NetworkWaiter();
    void wait();
    bool waitBreakSize(int a_break_size);
    qint64 bytesAvailable();
    QByteArray readAll();

private:
    QMutex m_mutex;
    QNetworkReply *m_reply;
    bool m_buffer_mode;
    QByteArray m_bytes;
	QEventLoop m_eventLoop;
    void p_connect_slots();
    void p_disconnect_slots();

private slots:
	void metaDataChanged();
    void replyReadyRead();
    void replyFinished();
};

class NetworkBatch
{
protected:
    QNetworkAccessManager *m_nam;
public:
    explicit NetworkBatch(QNetworkAccessManager *a_nam)
        : m_nam(a_nam)
    {
    }
    QNetworkReply *get(const QString &a_url)
    {
        return this->get(QUrl(a_url));
    }
    QNetworkReply *get(const QUrl &a_url)
    {
        return this->get(QNetworkRequest(a_url));
    }
    QNetworkReply *get(const QNetworkRequest &a_request)
    {
        QNetworkReply *v_reply = m_nam->get(a_request);
        NetworkWaiter v_watcher(v_reply);
        v_watcher.wait();
        return v_reply;
    }
    QNetworkReply *head(const QString &a_url)
    {
        return this->head(QUrl(a_url));
    }
    QNetworkReply *head(const QUrl &a_url)
    {
        return this->head(QNetworkRequest(a_url));
    }
    QNetworkReply *head(const QNetworkRequest &a_request)
    {
        QNetworkReply *v_reply = m_nam->head(a_request);
        NetworkWaiter v_watcher(v_reply);
        v_watcher.wait();
        return v_reply;
    }
};

#endif // NETWORKBATCHREQUEST_H
